﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;

namespace Nuts
{
    public class NutSpawner
    {
        const float MIN_TIME_BETWEEN_NUTS = 0.8f;
        const float MAX_TIME_BETWEEN_NUTS = 1.5f;

        const int WIDTH  = 80;
        const int HEIGHT = 60;

        private Game1 _game;
        private float _timer_next_wave;
        private Nut _hanged_nut;
        private Random _rand;
        private bool _active;
        private int _X;
        private int _Y;
        private Rectangle _hit_box;

        public NutSpawner(int X, int Y, Game1 game, Random randomGen)
        {
            _hit_box = new Rectangle(X, Y, NutSpawner.WIDTH, NutSpawner.HEIGHT);
            _X = X;
            _Y = Y;
            _game = game;
            _rand = randomGen;

            _active = true;
            _hanged_nut = null;
            ArmTimer();
        }

        public void Update(GameTime gameTime)
        {
            if (!_active)
                return;

            if (_hanged_nut != null)
                return;

            if (_game.GetActiveNutsCount() > Game1.MAX_NUTS)
                return;

            {
                _timer_next_wave -= (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (_timer_next_wave <= 0.0f)
                {
                    // spawn new nut on this spawner
                    _hanged_nut = new Nut(_game);
                    _hanged_nut.Spawn(_X+NutSpawner.WIDTH/2, _Y);
                    _game.AddNut(_hanged_nut);

                    ArmTimer();
                }
            }
        }

        public Rectangle GetHitBox()
        {
            return _hit_box;
        }

        public bool OnSlap(int X, int Y)
        {
            if (_hanged_nut == null)
                return false;

            if (!_hit_box.Contains(X, Y))
                return false;

            if(!_hanged_nut.IsRipe())
                return false;

            // cut the nut lose :D
            _hanged_nut.CutLose();
            _hanged_nut = null;
            return true;
        }

        private void ArmTimer()
        {
            _timer_next_wave = MathHelper.Lerp(MIN_TIME_BETWEEN_NUTS, MAX_TIME_BETWEEN_NUTS, (float)_rand.NextDouble());
        }
    }
}
